package com.ruoyi.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;


@Slf4j
@Configuration
public class RedisListenerConfig extends KeyExpirationEventMessageListener {

    @Autowired
    public RedisListenerConfig(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired(required = false)
    private OrderRedisMessageListener wxRedisMessageLister;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        log.debug("[redis过期消息监听] 消费者监听key：{}", key);
        try {
            // 获取自己实现类获取实现类全部方法
            Method[] methods = wxRedisMessageLister.getClass().getDeclaredMethods();
            log.debug("[redis过期消息监听] 消费者监听方法：{}", Arrays.toString(methods));
            for (Method method : methods) {
                // 获取方法的注解判断是否与过期key一致
                Annotation annotation = method.getAnnotation(OrderRedisListener.class);
                if (annotation == null) {
                    continue;
                }
                if (key.contains(((OrderRedisListener) annotation).key())) {
                    method.invoke(wxRedisMessageLister, key);
                    log.debug("[redis消息过期监听] 消费成功：key [{}],message:[{}]", key, message);
                }
                if (key.contains(((OrderRedisListener) annotation).ext())) {
                    method.invoke(wxRedisMessageLister, key);
                    log.debug("[redis消息过期监听] 消费成功：key [{}],message:[{}]", key, message);
                }
            }
        } catch (Exception e) {
            log.error("[redis消息过期监听] 消费失败：key [{}],message:[{}]", key, message,e);
        }
        super.onMessage(message, pattern);
    }
}


